package red.mlz.console.controller.category;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import red.mlz.console.annotations.VerifiedUser;
import red.mlz.console.domain.cateogory.CategorylListVO;
import red.mlz.module.module.category.entity.Category;
import red.mlz.module.module.category.service.CategoryService;
import red.mlz.module.module.user.entity.User;
import red.mlz.module.utils.BaseUtils;
import red.mlz.module.utils.Response;

import java.math.BigInteger;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 或
     *
     * @return
     */
    @RequestMapping("/category/list")
    public Response categoryList(@VerifiedUser User loginUser) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        List<CategorylListVO> result;
        try {
            List<Category> categoryList = categoryService.categoryList();
            // 按父ID分组（避免递归中重复遍历）
            Map<BigInteger, List<Category>> parentIdToCategories = categoryList.stream()
                    .collect(Collectors.groupingBy(Category::getParentId));
            // 构建分类树
            result = buildTreeNodes(parentIdToCategories, BigInteger.valueOf(0));
        } catch (Exception e) {
            // 或者使用日志框架记录详细信息
            log.info("异常: " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return new Response(1001, result);
    }


    @RequestMapping("/category/create")
    public Response categoryCreate(@VerifiedUser User loginUser,
                                   @RequestParam("name") String name,
                                   @RequestParam(value = "imageUrl", required = false) String imageUrl,
                                   @RequestParam(value = "parentId", required = false) BigInteger parentId) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        //parameters check
        name = name.trim();
        if (BaseUtils.isEmpty(name)) {
            return new Response(3051);
        }

        try {
            categoryService.editCategory(null, name, imageUrl, parentId);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);

        }
    }

    @RequestMapping("/category/modify")
    public Response categoryModify(@VerifiedUser User loginUser,
                                   @RequestParam(name = "categoryId") BigInteger categoryId,
                                   @RequestParam(value = "name", required = false) String name,
                                   @RequestParam(value = "imageUrl", required = false) String imageUrl,
                                   @RequestParam(value = "parentId", required = false) BigInteger parentId) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        Category old = categoryService.getById(categoryId);
        if (BaseUtils.isEmpty(old)) {
            return new Response(4004);
        }
        try {
            categoryService.editCategory(categoryId, name, imageUrl, parentId);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);

        }
    }


    @RequestMapping("/category/delete")
    public Response categoryDelete(@VerifiedUser User loginUser,
                                   @RequestParam(name = "categoryId") BigInteger categoryId) {
        if (BaseUtils.isEmpty(loginUser)) {
            return new Response(1002);
        }
        if (BaseUtils.isEmpty(categoryId)) {
            return new Response(4004);
        }
        try {
            categoryService.delete(categoryId);
            return new Response(1001);
        } catch (Exception exception) {
            return new Response(4004);
        }
    }

    private List<CategorylListVO> buildTreeNodes(Map<BigInteger, List<Category>> parentIdToCategories, BigInteger parentId) {
        List<Category> categoryList = parentIdToCategories.getOrDefault(parentId, Collections.emptyList());
        List<CategorylListVO> categorylListVOList = categoryList.stream()
                .map(category -> {
                    CategorylListVO categorylListVO = new CategorylListVO()
                            .setId(category.getId())
                            .setName(category.getName())
                            .setImageUrl(category.getImageUrl())
                            .setParentId(category.getParentId())
                            .setChildrenList(buildTreeNodes(parentIdToCategories, category.getId()));
                    return categorylListVO;
                }).collect(Collectors.toList());
        return categorylListVOList;
    }


}
